#include <iostream>
#include <random>
#include <cstring>
#include <ctime>
#include <dds/dds.h>
#include "end_atomic_0813_log_management_service.h"
#include "../../../include/log_client/LogClient.h"

// DDS实体句柄
static dds_entity_t participant;
static dds_entity_t topic;
static dds_entity_t subscriber;
static dds_entity_t reader;

// 简化结构体名称
typedef end_atomic_0813_log_management_service_LogManagerOutput TransportOutput;

// 清理DDS资源
static void cleanup()
{
    if (reader != DDS_HANDLE_NIL)
        dds_delete(reader);
    if (subscriber != DDS_HANDLE_NIL)
        dds_delete(subscriber);
    if (topic != DDS_HANDLE_NIL)
        dds_delete(topic);
    if (participant != DDS_HANDLE_NIL)
        dds_delete(participant);
}

// 生成随机字符串（用于timestamp和content）
static char* generate_random_string(size_t max_len, bool is_timestamp = false)
{
    if (is_timestamp)
    {
        // 生成格式如"2024-08-13 12:34:56"的时间戳
        time_t now = time(nullptr);
        struct tm* tm_info = localtime(&now);
        // 随机偏移一些时间（±30天）
        std::mt19937 rng(std::random_device{}());
        std::uniform_int_distribution<int> day_dist(-30, 30);
        tm_info->tm_mday += day_dist(rng);
        mktime(tm_info); // 处理日期溢出
        
        char* buf = (char*)malloc(20); // 足够容纳时间字符串
        strftime(buf, 20, "%Y-%m-%d %H:%M:%S", tm_info);
        return buf;
    }
    else
    {
        // 生成随机日志内容
        const char* prefixes[] = {"系统启动", "数据处理", "连接状态", "错误恢复", "用户操作"};
        std::mt19937 rng(std::random_device{}());
        std::uniform_int_distribution<size_t> prefix_dist(0, 4);
        std::uniform_int_distribution<int> num_dist(100, 999);
        
        char content[128];
        snprintf(content, sizeof(content), "%s: 操作ID=%d，状态正常", 
                 prefixes[prefix_dist(rng)], num_dist(rng));
        
        char* buf = (char*)malloc(strlen(content) + 1);
        strcpy(buf, content);
        return buf;
    }
}

// 生成随机结果数据（用于测试）
TransportOutput generate_random_transport_data()
{
    static std::mt19937 rng(std::random_device{}());
    
    // 定义随机分布（适配新结构体成员）
    std::uniform_int_distribution<int32_t> log_id_dist(1000, 9999);       // log_id: 1000-9999的整数
    std::uniform_int_distribution<int32_t> handle_result_dist(0, 5);      // 处理结果: 0-5的整数
    std::uniform_int_distribution<int32_t> return_type_dist(0, 3);        // 返回类型：0-3

    TransportOutput data;
    data.log_id = log_id_dist(rng);
    data.timestamp = generate_random_string(20, true);
    data.content = generate_random_string(128, false);
    data.handle_result = handle_result_dist(rng);
    data.return_type = return_type_dist(rng);
    
    return data;
}

int main()
{
    // 初始化日志
    LogClient::getInstance().init("end_atomic_0813_log_management_service", "end_atomic_0813_log_management_service");

    dds_return_t rc;
    void* samples[1];       // 存储DDS样本的数组（最多1个样本）
    dds_sample_info_t info; // 样本元信息

    // 1. 初始化DDS参与者
    participant = dds_create_participant(DDS_DOMAIN_DEFAULT, NULL, NULL);
    if (participant < 0)
    {
        std::cerr << "错误：创建参与者失败，原因：" << dds_strretcode(-participant) << std::endl;
        LogClient::getInstance().logError("创建参与者失败，原因：" + std::string(dds_strretcode(-participant)));
        cleanup();
        return EXIT_FAILURE;
    }

    // 2. 创建主题（与发布者保持一致）
    topic = dds_create_topic(
        participant,
        &end_atomic_0813_log_management_service_LogManagerOutput_desc,
        "end_atomic_0813_log_management_service",  // 主题名称
        NULL, NULL);
    if (topic < 0)
    {
        std::cerr << "错误：创建主题失败，原因：" << dds_strretcode(-topic) << std::endl;
        LogClient::getInstance().logError("创建主题失败，原因：" + std::string(dds_strretcode(-topic)));
        cleanup();
        return EXIT_FAILURE;
    }

    // 3. 创建订阅者
    subscriber = dds_create_subscriber(participant, NULL, NULL);
    if (subscriber < 0)
    {
        std::cerr << "错误：创建订阅者失败，原因：" << dds_strretcode(-subscriber) << std::endl;
        LogClient::getInstance().logError("创建订阅者失败，原因：" + std::string(dds_strretcode(-subscriber)));
        cleanup();
        return EXIT_FAILURE;
    }

    // 4. 创建数据读取器
    dds_qos_t* qos = dds_create_qos();
    dds_qset_reliability(qos, DDS_RELIABILITY_RELIABLE, DDS_SECS(10));
    dds_qset_history(qos, DDS_HISTORY_KEEP_LAST, 10);

    reader = dds_create_reader(subscriber, topic, qos, NULL);
    dds_delete_qos(qos);

    if (reader < 0)
    {
        std::cerr << "错误：创建读取器失败，原因：" << dds_strretcode(-reader) << std::endl;
        LogClient::getInstance().logError("创建读取器失败，原因：" + std::string(dds_strretcode(-reader)));
        cleanup();
        return EXIT_FAILURE;
    }

    std::cout << "DDS结果分布服务订阅者已启动，等待接收数据..." << std::endl;
    std::cout << "主题: end_atomic_0813_log_management_service" << std::endl;
    std::cout << "按Ctrl+C终止程序" << std::endl;
    LogClient::getInstance().logInfo("DDS结果分布服务订阅者已启动，等待接收数据...\n主题: end_atomic_0813_log_management_service\n按Ctrl+C终止程序");

    // 5. 循环读取数据
    int count = 0;
    while (true)
    {
        // 分配样本内存
        samples[0] = end_atomic_0813_log_management_service_LogManagerOutput__alloc();
        if (samples[0] == NULL)
        {
            std::cerr << "错误：分配样本内存失败" << std::endl;
            LogClient::getInstance().logError("分配样本内存失败");
            cleanup();
            return EXIT_FAILURE;
        }

        // 从读取器中获取数据
        rc = dds_take(reader, samples, &info, 1, 1);
        if (rc < 0)
        {
            std::cerr << "错误：dds_take失败，原因：" << dds_strretcode(-rc) << std::endl;
            LogClient::getInstance().logError("dds_take失败，原因：" + std::string(dds_strretcode(-rc)));
            end_atomic_0813_log_management_service_LogManagerOutput_free(samples[0], DDS_FREE_ALL);
            cleanup();
            return EXIT_FAILURE;
        }

        // 检查是否有有效数据
        if (rc > 0 && info.valid_data)
        {
            // 转换为目标结构体类型
            TransportOutput* data = (TransportOutput*)samples[0];
            count++;

            // 构建日志信息
            const char* type_str[] = {"成功", "警告", "错误", "超时"};
            int32_t type_idx = (data->return_type >= 0 && data->return_type < 4) ? data->return_type : 0;
            
            // 处理可能的空指针
            const char* timestamp_str = (data->timestamp != NULL) ? data->timestamp : "NULL";
            const char* content_str = (data->content != NULL) ? data->content : "NULL";

            std::string log_info = "接收到结果数据，第" + std::to_string(count) + "次\n";
            log_info += "源时间戳: " + std::to_string(info.source_timestamp) + "\n";
            log_info += "日志ID: " + std::to_string(data->log_id) + "\n";
            log_info += "日志时间戳: " + std::string(timestamp_str) + "\n";
            log_info += "日志内容: " + std::string(content_str) + "\n";
            log_info += "处理结果: " + std::to_string(data->handle_result) + "\n";
            log_info += "返回类型: " + std::string(type_str[type_idx]) + " (" + std::to_string(data->return_type) + ")\n";

            std::cout << log_info << std::endl;
            LogClient::getInstance().logInfo(log_info);
        }

        // 释放样本内存（DDS会自动释放内部字符串）
        end_atomic_0813_log_management_service_LogManagerOutput_free(samples[0], DDS_FREE_ALL);

        // 休眠100ms避免CPU占用过高
        dds_sleepfor(DDS_MSECS(100));
    }

    // 清理资源（实际不会执行到）
    cleanup();
    return EXIT_SUCCESS;
}